import os

from ninja import Router
from apps.commom.customer_service import CommonQuestionResponseSerializer
from apps.schemas import R
from apps.user_applets.customer_service.schema import CustomerServiceScoreSchema
from models.models import CommonQuestion, CustomerServiceFeedbackRecord
from utils.auth import AppletAuthBearer
from utils.decorators import handle_exception

applets_customer_service_router = Router(tags=["小程序客服"], auth=AppletAuthBearer())


@applets_customer_service_router.get("/service_switch", summary="获取客服开关状态")
@handle_exception("获取客服开关状态失败")
def get_service_switch(request):
    if not os.path.exists("conf/service_switch"):
        return R.fail("获取客服开关状态失败")
    with open("conf/service_switch", "r") as f:
        return R.ok(f.read())


@applets_customer_service_router.get("/common_question", summary="获取常见问题")
@handle_exception("获取常见问题失败")
def get_common_questions(request):
    """
    获取常见问题
    """
    return R.ok(CommonQuestionResponseSerializer(CommonQuestion.objects.all(), many=True).data)


# @applets_customer_service_router.post("/user_ask_question", summary="用户提交问题")
# @handle_exception("用户提交问题失败")
# def add_common_question(request):
#     """
#     用户提交问题
#     """
#     token = request.headers.get("token")
#     user_id, token = token.split("::")
#     user = User.objects.get(pk=user_id)
#     key = settings.REDIS_APPLETS_LOGIN_TOKEN_KEY.format(user_id=request.user.id)
#     if cache.get(key) != token:
#         return R.ok({"error": "Invalid token", "code": 401})
#     if request.is_websocket:
#         number = str(snowflake())[-6:]
#         ws = request.websocket
#         question = ws.wait()
#         record = CustomerServiceRecords.objects.create(customer_number=number, question=question, question_user=user)
#         # 对接AI客服获取答案 https://blog.csdn.net/q506610466/article/details/132790633
#         callback = QianMaiStreamingStdOutCallbackHandler()
#
#         llm = ChatOpenAI(model='gpt-3.5-turbo',
#                          streaming=True,
#                          callbacks=[callback],
#                          max_tokens=1024)
#         res = llm.invoke(question.question)
#         # todo 添加客服反馈记录
#         CustomerServiceFeedbackRecord.objects.create(customer_number=number, feedback_user=user,
#                                                      feedback_content=res.content)
#         record.answer = res.content
#         record.answer_time = timezone.now()
#         record.save()
#         ws.send(number)
#         while not callback.finish:  # or self.tokens:
#             if callback.tokens:
#                 ws.send(callback.tokens.pop(0))


@applets_customer_service_router.post("/customer_score", summary="客服打分")
@handle_exception("客服打分失败")
def get_common_question(request, data: CustomerServiceScoreSchema):
    """
    获取常见问题
    """
    if data.score < 1 or data.score > 5:
        return R.fail(msg="评分范围1-5")
    CustomerServiceFeedbackRecord.objects.create(feedback_user=request.user, customer_number=data.customer_number,
                                                 feedback_content=data.feedback)
    return R.ok(msg="评分成功")
